package com.ruoyi.web.controller.expertmodel;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.XssUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.diagmanage.domain.StateInventory;
import com.ruoyi.diagmanage.domain.StateReport;
import com.ruoyi.expertmodel.domain.HealthModel;
import com.ruoyi.expertmodel.service.HealthModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.ruoyi.common.core.domain.AjaxResult.success;
@Slf4j
@RestController
@RequestMapping("/healthModelController")
public class HealthModelController extends BaseController {

    @Resource
    private HealthModelService healthModelService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    public static FileInputStream convertToFileInputStream(InputStream inputStream) throws IOException {
        File tempFile = File.createTempFile("temp", ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return new FileInputStream(tempFile);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[]{"admin"});
    }

    @GetMapping("/queryHealthModel")
    public TableDataInfo queryHealthModel( HealthModel healthModel) throws ExecutionException, InterruptedException {

            // do something
            startPage();
            //CompletableFuture<List<HealthModel>> healthModels = healthModelService.queryHealthModel(healthModel);
            //return getDataTable(healthModels.get());
        List<HealthModel> healthModels = healthModelService.queryHealthModel(healthModel);
        return getDataTable(healthModels);

    }

    @PostMapping("/deleteHealthModel")
    public AjaxResult deleteHealthModel(@RequestBody HealthModel healthModel)
    {
        boolean b = healthModelService.deleteHealthModel(healthModel);
        if(b){
            return success("删除成功！");
        }else{
            return success("删除失败！");
        }

    }

    @PostMapping("/addHealthModel")
    public AjaxResult addHealthModel(@RequestBody HealthModel healthModel)
    {
        boolean b = healthModelService.save(healthModel);
        if(b){
            return success("新增成功！");
        }else{
            return success("新增失败！");
        }

    }

    @PostMapping("/updateHealthModel")
    public AjaxResult updateHealthModel(@RequestBody HealthModel healthModel)
    {
        //return CompletableFuture.supplyAsync(() -> {
            boolean b = healthModelService.updateById(healthModel);
            if(b){
                return success("修改成功！");
            }else{
                return success("修改失败！");
            }
        //}, taskExecutor);
    }

    @PostMapping("/copyHealthModel")
    public AjaxResult copyHealthModel(@RequestBody HealthModel healthModel)
    {
        UUID uuid =UUID.randomUUID();
        healthModel.setId(Objects.toString(uuid));
        healthModelService.copyHealthModel(healthModel);
        return success("修改成功！");
    }

    @PostMapping("/queryHealthModelById")
    public AjaxResult queryHealthModelById(@RequestBody HealthModel healthModel)
    {
        HealthModel model = healthModelService.getById(healthModel.getId());
        return success(model);

    }

    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, HealthModel healthModel)
    {
        List<HealthModel> healthModels = healthModelService.queryHealthModel(healthModel);

        ExcelUtil<HealthModel> util = new ExcelUtil<HealthModel>(HealthModel.class);

        util.exportExcel(response, healthModels, "健康模型");
    }

    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        String c= file.getOriginalFilename();
        int index = c.lastIndexOf(".");
        String suffix = c.substring(index + 1);

        if (!"xlsx".equals(suffix) && !"xls".equals(suffix)) {
            return AjaxResult.error("仅允许上传excel文件");
        }
        //
        ExcelUtil<HealthModel> util = new ExcelUtil<HealthModel>(HealthModel.class);
        //测，xssf对象xlsx
        // hssf 对应都可以  这里 xls
        InputStream is = null;
        InputStream is2 = null;
        FileInputStream fileInputStream = null;
        try {

            is = file.getInputStream();
            is2 = file.getInputStream();
            fileInputStream = convertToFileInputStream(is);
            boolean t = false;
            if("xlsx".equals(suffix)){
                t = XssUtil.checkXSSFExcelXssFlag(fileInputStream);
            }else if("xls".equals(suffix)){
                t = XssUtil.checkXSSFExcelXssFlag(fileInputStream);
            }

            if(t){
                List<HealthModel> healthList = util.importExcel(is2);
                boolean flag = healthModelService.batchImport(healthList);

                if(flag){
                    return success("成功");
                }else{
                    return success("失敗");
                }
            }

        }catch (Exception e){
            log.info(e.toString());
        } finally {

            if(is !=null ){
                try{
                    is.close();
                }catch (Exception e){
                    log.info(e.toString());
                }
            }
            if(fileInputStream !=null ){
                try{
                    fileInputStream.close();
                }catch (Exception e){
                    log.info(e.toString());
                }
            }
            if(is2 !=null ){
                try{
                    is2.close();
                }catch (Exception e){
                    log.info(e.toString());
                }

            }

        }
        return AjaxResult.error("失败");
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HealthModel> util = new ExcelUtil<HealthModel>(HealthModel.class);
        util.importTemplateExcel(response, "健康模型");
    }







}
